package kr.saeildamil.androidstudy_second.br_service;

import kr.saeildamil.androidstudy_second.R;
import kr.saeildamil.androidstudy_second.br_service.LocalService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class BoundServiceTest extends Activity implements OnClickListener{
	LocalService mService;
	boolean mBound = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch2930_boundservicetest);
		findViewById(R.id.boundservicetest_start).setOnClickListener(this);
	}
	
	@Override
	protected void onResume() {
		Log.d("BoundServiceTest", "onResume()");
		super.onStart();
		Intent intent = new Intent(this, LocalService.class);
		bindService(intent,mConn, Context.BIND_AUTO_CREATE);
	}
	
	

	@Override
	protected void onPause() {
		Log.d("BoundServiceTest", "onPause()");
		super.onStop();
		if(mBound){
			unbindService(mConn);
		}
	}



	ServiceConnection mConn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.d("BoundServiceTest", "onServiceDisconnected()");
			mBound = false;	
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.d("BoundServiceTest", "onServiceConnected()");
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
		}
	};
	
	@Override
	public void onClick(View v) {
		if(mBound){
			Toast.makeText(this, Integer.toString(mService.getRandomnumber()), Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(this, "서비스와 연결되지 않음", Toast.LENGTH_SHORT).show();
		}
	}
}
